<template>
  <div
    class="file-input"
    @click="uploadClick"
    @drop.prevent="uploadDrop"
    @dragover.prevent
    @dragleave.prevent
  >
    <slot>
      <span class="file-input-text">请将文件拖至这里或点击这里</span>
    </slot>
    <input
      ref="upload"
      class="file-input-file"
      type="file"
      name="file"
      @change="uploadSubmit"
    />
  </div>
</template>

<script>
export default {
  name: 'FileInput',
  methods: {
    // 点击Excel上传区
    uploadClick() {
      this.$refs.upload.click()
    },
    // 通过点击的方式选择文件
    uploadSubmit() {
      const files = this.$refs.upload.files
      this.emitChooseFiles(files[0])
    },
    // 通过拖拽的方式选择文件
    uploadDrop(evt) {
      const files = evt.dataTransfer.files
      this.emitChooseFiles(files[0])
    },
    // 抛出选择文件事件
    emitChooseFiles(file) {
      this.$emit('choose', file) // 抛出事件
      this.$refs.upload.value = '' // 清空值，防止下次选择同一文件时失败
    }
  }
}
</script>

<style>
.file-input {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 300px;
  height: 200px;
  border-radius: 16px;
  border: 1.5px dashed #aaa;
  user-select: none;
  cursor: pointer;
}
.file-input-file {
  display: none;
}
</style>
